package org.zebra.mybatis.plus.core;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.zebra.common.core.PageQuery;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页查询VO类
 *
 * @author zhanghongbin
 */
public class MPageQuery extends PageQuery<Page> {

    public <P> Page<P> build() {
        Integer pageNum = ObjectUtil.defaultIfNull(this.getPage(), DEFAULT_PAGE_NUM);
        Integer pageSize = ObjectUtil.defaultIfNull(this.getSize(), DEFAULT_PAGE_SIZE);
        if (pageNum <= 0) {
            pageNum = DEFAULT_PAGE_NUM;
        }
        Page<P> page = new Page<>(pageNum, pageSize);
        List<OrderItem> orderItems = buildOrderItem();
        if (CollUtil.isNotEmpty(orderItems)) {
            page.addOrder(orderItems);
        }
        return page;
    }

    /**
     * 构建排序
     * <p>
     * 支持的用法如下:
     * {order:"asc",sort:"id"} order by id asc
     * {order:"asc",sort:"id,createTime"} order by id asc,create_time asc
     * {order:"desc",sort:"id,createTime"} order by id desc,create_time desc
     * {order:"asc,desc",sort:"id,createTime"} order by id asc,create_time desc
     */
    private List<OrderItem> buildOrderItem() {
        if (CharSequenceUtil.isEmpty(this.getSort()) || CharSequenceUtil.isEmpty(this.getOrder())) {
            return null;
        }

        String[] orderByArr = this.getSort().split(",");
        String[] isSortArr = this.getOrder().split(",");
        if (isSortArr.length != 1 && isSortArr.length != orderByArr.length) {
            return new ArrayList<>();
        }

        List<OrderItem> list = new ArrayList<>();
        // 每个字段各自排序
        for (int i = 0; i < orderByArr.length; i++) {
            String orderByStr = orderByArr[i];
            String isSortStr = isSortArr.length == 1 ? isSortArr[0] : isSortArr[i];
            if ("asc".equals(isSortStr)) {
                list.add(OrderItem.asc(orderByStr));
            } else if ("desc".equals(isSortStr)) {
                list.add(OrderItem.desc(orderByStr));
            } else {
                return new ArrayList<>();
            }
        }
        return list;
    }
}
